package main

import (
	"io"
	"log"
	"net/http"
	"net/url"
	"strings"
)

// 定义常量 token
const validToken = "your-secret-token"

// 验证请求中的 token
func authenticate(r *http.Request) bool {
	token := r.Header.Get("Authorization")
	return token == validToken
}

func proxyHandler(w http.ResponseWriter, r *http.Request) {
	if !authenticate(r) {
		// http.Error(w, "Unauthorized", http.StatusUnauthorized)
		// return
	}

	// 获取完整的查询字符串
	proxyQuery := r.URL.RawQuery

	// 找到 proxy_query= 的位置
	startIndex := strings.Index(proxyQuery, "proxy_query=")
	if startIndex == -1 {
		http.Error(w, "缺少 proxy_query 参数", http.StatusBadRequest)
		return
	}

	// 截取后面的内容作为后端 URL
	backendURL := proxyQuery[startIndex+len("proxy_query="):]
	decodedString, err := url.QueryUnescape(backendURL)
	if err != nil {
		log.Println("Error:", err)
		return
	}

	// 创建新的请求
	req, err := http.NewRequestWithContext(r.Context(), r.Method, decodedString, r.Body)
	if err != nil {
		http.Error(w, "创建请求失败", http.StatusInternalServerError)
		return
	}

	// 复制请求头
	for key, values := range r.Header {
		for _, value := range values {
			req.Header.Add(key, value)
		}
	}

	// 发送请求到后端服务器
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		http.Error(w, "请求后端服务器失败", http.StatusInternalServerError)
		return
	}
	defer resp.Body.Close()

	// 复制后端服务器的响应头
	for key, values := range resp.Header {
		for _, value := range values {
			w.Header().Add(key, value)
		}
	}

	// 复制后端服务器的响应体
	w.WriteHeader(resp.StatusCode)
	if _, err := io.Copy(w, resp.Body); err != nil {
		log.Printf("复制响应体失败: %v", err)
	}
}

func main() {
	http.HandleFunc("/", proxyHandler)

	log.Println("服务器启动在 :8080 端口")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatalf("服务器启动失败: %v", err)
	}
}
